$(function() {
    var cols = 6;
    var rows_delete = 0;
    var mode = "add";
    var m_id = 0;
    var url = 'controls/stock_model.php';
    var oTable = $('#resultData').dataTable();
    var nEditing = null;
    
     LoadData(0,'',0,'');

    $("#txtAmt , .newAmt").live('keypress',function(e){

		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
				return false;
		}
    });
    
    $.get(url, {"m": "pdtype"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj != null) {
            $.each(obj, function(index, text) {
                $("#cboType").append(
                    $('<option></option>').val(text).html(index)
                );
            });
        }
    });
    $("#cboType").append($('<option></option>').val(0).html(' '));
   
    $(".btnEdit").live('click',function(e){
        e.preventDefault();
        var nRow = $(this).parents('tr')[0];
        /* No edit in progress - let's start one */
        editRow( oTable, nRow );
        nEditing = nRow; 
        
    });
    $(".btnUndo").live('click',function(e){
        e.preventDefault();
        restoreRow( oTable, nEditing );
         
    });
    function editRow ( Table, nRow )
    {
            var aData = Table.fnGetData(nRow);
            var jqTds = $('>td', nRow);
           
            jqTds[4].innerHTML = '<input type="text" style="width:40px;margin-bottom:0px !important;" maxlength=4 class="text-right newAmt"  value="'+aData[6]+'">';
            jqTds[7].innerHTML = "<img src='img/save24.png' class='btnSave' style='cursor:pointer;'/>&nbsp;<img src='img/undo.png' class='btnUndo' style='cursor:pointer;'/>";
    }
    
    function restoreRow ( Table, nRow )
    {
        var aData = Table.fnGetData(nRow);

        oTable.fnUpdate( aData[6], nRow, 6, false );
        oTable.fnUpdate( "<a href='#' ><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>", nRow, 9, false );

        oTable.fnDraw();
    }
    
    function saveRow(Table,nRow){
        var jqInputs = $('input', nRow);
        var val = 0;
        var aData = Table.fnGetData(nRow);
        
        if (jqInputs[0].value !='')
               val = jqInputs[0].value;
          
         var total = parseFloat(aData[6]) * val;      
		oTable.fnUpdate( val, nRow, 6, false );
        oTable.fnUpdate( total.toFixed(2), nRow, 8, false );
        oTable.fnUpdate( "<a href='#' ><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>", nRow, 9, false );
 
         $.ajax({
                type: 'POST',
                cache: false,
                url: url,
                data: {"m":"up_stock","id":aData[1] , "pid":aData[2] , "amt": val},
                success: function(data) {
                    oTable.fnDraw();
                }
            });
    }
    $(".btnSave").live('click', function() {
        
        saveRow( oTable, nEditing );
        nEditing = null;

    });

    
    $("#btnSearch").click(function() {
          var _type = $("#cboType").val();
          var _name = $("#txtName").val();
          var _compare = $("#cboCompare").val();
          var _val = $("#txtAmt").val();

          LoadData(_type, _name, _compare, _val);
      });
      
    function LoadData(type, name, c, val) {
        $("#resultData tbody tr").remove();


        $('#resultData').dataTable({
            "bProcessing": true,
            "bFilter": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_stock"},
                {"name": "type", "value": type},
                {"name": "name", "value": name},
                {"name": "compare", "value": c},
                {"name": "value", "value": val}
                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
                {"bVisible": false, "aTargets": [2]},
                {"bSortable": true, "aTargets": [3], "sClass": "text-center"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [5], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [6], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [7], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [8], "sClass": "text-right"},
                {"aTargets": [9],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						if (_te==1) 
							return "<a href='#' ><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
						else 
							return "";
                    }
                }
            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = oSettings.aiDisplay.length; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }
        });

    }
 
});


